using UnityEngine;
using System.Collections;

public class TroopInitializer : MonoBehaviour
{
    [Header("区域管理器引用")]
    [SerializeField] private Area_Manager areaManager;

    [Header("士兵预制体")]
    [SerializeField] private GameObject infantryPrefab;
    [SerializeField] private GameObject archerPrefab;
    [SerializeField] private GameObject cavalryPrefab;

    [Header("初始化设置")]
    [SerializeField] private bool initializeOnStart = true;
    [SerializeField] private float initializationDelay = 1.0f;

    void Start()
    {
        // 如果没有手动设置区域管理器，尝试自动查找
        if (areaManager == null)
        {
            areaManager = FindObjectOfType<Area_Manager>();
            if (areaManager == null)
            {
                Debug.LogError("找不到Area_Manager组件，无法初始化士兵");
                return;
            }
        }

        // 设置预制体引用
        if (areaManager != null)
        {
            areaManager.infantryPrefab = infantryPrefab;
            areaManager.archerPrefab = archerPrefab;
            areaManager.cavalryPrefab = cavalryPrefab;
        }

        // 如果设置为在开始时初始化，则启动初始化协程
        if (initializeOnStart)
        {
            StartCoroutine(InitializeTroopsWithDelay());
        }
    }

    // 延迟初始化士兵，确保场景完全加载
    private IEnumerator InitializeTroopsWithDelay()
    {
        yield return new WaitForSeconds(initializationDelay);
        InitializeAllTroops();
    }

    // 初始化所有士兵
    public void InitializeAllTroops()
    {
        if (areaManager != null)
        {
            Debug.Log("开始初始化所有区域的士兵...");
            areaManager.SpawnAllTroops();
            Debug.Log("所有区域的士兵初始化完成");
        }
        else
        {
            Debug.LogError("区域管理器为空，无法初始化士兵");
        }
    }

    // 初始化特定国家的士兵
    public void InitializeCountryTroops(string country)
    {
        if (areaManager != null)
        {
            Debug.Log($"开始初始化{country}的士兵...");
            var countryAreas = areaManager.GetAreasByCountry(country);
            foreach (var area in countryAreas)
            {
                areaManager.SpawnTroopsInArea(area);
            }
            Debug.Log($"{country}的士兵初始化完成");
        }
        else
        {
            Debug.LogError("区域管理器为空，无法初始化士兵");
        }
    }
}